package com.maxjay.component.metadata.core;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.maxjay.component.metadata.core.formatter.FieldFormatter;
import com.maxjay.component.metadata.core.parser.FieldFormatterParser;
import com.maxjay.system.core.spring.BeanContext;

public class FormatterFactoryImpl implements FormatterFactory {

	private static final Logger LOG = Logger.getLogger(FormatterFactoryImpl.class);
	
	private static final String FORMATTER_PARSER_KEY = "fieldFormatterParser";
	
	private BeanContext beanContext;
	
	private Map<String, FieldFormatter> fieldFormatterMap = new HashMap<String, FieldFormatter>();
	
	public FormatterFactoryImpl(BeanContext beanContext) {
		this.beanContext = beanContext;
	}
	
	public FieldFormatter getFieldFormatter(String formatterId) {
		FieldFormatter fieldFormatter = null;
		if (StringUtils.isBlank(formatterId)) {
			fieldFormatter = fieldFormatterMap.get(formatterId);
			if(fieldFormatter == null) {
				LOG.info("缓存中没有属性格式化器[" + formatterId + "]，系统重新加载...");
				fieldFormatter = loadFieldFormatter(formatterId);
			}
		}
		return fieldFormatter;
	}
	
	public FieldFormatter loadFieldFormatter(String formatterId) {
		FieldFormatterParser formatterParser = beanContext.getBean(FORMATTER_PARSER_KEY, FieldFormatterParser.class);
		FieldFormatter fieldFormatter = formatterParser.parserFieldFormatter(formatterId);
		LOG.info("加载属性格式化器[" + formatterId + "]");
		fieldFormatterMap.put(formatterId, fieldFormatter);
		return fieldFormatter;
	}
	
}
